package dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import models.Conversation;

import org.bson.types.ObjectId;
import org.jongo.MongoCollection;

import uk.co.panaxiom.playjongo.PlayJongo;
import dao.ConversationDao;

public class ConversationDaoImpl implements ConversationDao {

	private static final MongoCollection conversations;
	static {
		conversations = PlayJongo.getCollection("conversations");
	}
	
	@Override
	public void insert(Conversation conversation) {
		conversations.save(conversation);
		
	}

	@Override
	public List<Conversation> selectByDestinateId(String destinateId) {
		List<Conversation> result = new ArrayList<Conversation>();
		Iterator<Conversation> iter = conversations.find("{destinateId:#}}",new ObjectId(destinateId)).as(Conversation.class).iterator();
		while (iter.hasNext()) {
			result.add(iter.next());
		}
		return result;
	}
	
	@Override
	public List<Conversation> selectInByRoutingKey(List<String> routingKeys){
		List<Conversation> result = new ArrayList<Conversation>();
		Iterator<Conversation> iter = conversations.find("{routingKey: {$in:#}}", routingKeys).limit(100).sort("{datetime: -1}").as(Conversation.class).iterator();
		while (iter.hasNext()) {
			result.add(iter.next());
		}
		return result;
	}

}
